package com.my.main.component.filter;

import com.alibaba.fastjson.JSONObject;
import com.my.main.common.encrypt.DES3;
import com.my.main.common.utils.JSONUtil;
import com.my.main.common.utils.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@WebFilter(filterName = "myFilter1", urlPatterns = "/*")
public class MyFilter implements Filter {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private Environment env;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) {


        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        log.info("刚进入doFilter方法" + request.getRequestURI());
        try {

            // 图片请求处理`
            if (request.getRequestURI().indexOf("fileUp") > -1) {

                log.info("fileUp");

                String url = URLDecoder.decode(request.getRequestURI(), "utf-8");

                // 整理路径
                //int prthCur = request.getRequestURI().indexOf("/fileUp/");
                url = url.substring(url.indexOf("/fileUp/"), url.length());

                String path = url.substring(7, url.length());

                //请求体参数
                MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
                //文件
                param.add("app_id", env.getProperty("cs.appId"));
                // 其他参数
                param.add("path", path);
                //请求头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);
                HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(param, headers);
                //发送请求
                ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(env.getProperty("fss.base.url") + "/fss/getUrl", formEntity, String.class);
                JSONObject json = new JSONObject();
                String dataStr = URLDecoder.decode(stringResponseEntity.getHeaders().get("data").toString(), "UTF-8");
                log.info("dataStr===" + dataStr);

                List<Map<String, Object>> list = (List<Map<String, Object>>) JSONUtil.parseList(dataStr, Map.class);
                String picPath = list.get(0).get("fullURL").toString();
                picPath = new String(picPath.getBytes("utf-8"), "iso-8859-1");

                // 处理请求
                log.info("picPath将要跳转的请求===" + picPath);
                response.sendRedirect(picPath);

            } else if (request.getRequestURI().indexOf("downloadZip") > -1) {

                // 获取参数
                String[] paths = request.getParameterValues("paths");
                List<String> pathList = Arrays.asList(paths);
                if (pathList.isEmpty()) {
                    return;
                }

                // 请求路径
                String redirectUrl = env.getProperty("fss.out.url") + "/fss/batchDownload";
                // 请求参数
                String urlParams = "?app_id=" + env.getProperty("cs.appId");
                // json加密参数
                JSONObject json = new JSONObject();
                json.put("pathList", pathList);
                json.put("random", StrUtil.getRandomNumberString(6));
                json.put("timestamp", System.currentTimeMillis());

                try {
                    String encryptParams = DES3.encrypt(json.toString(), env.getProperty("app_secret"));
                    urlParams += "&params=" + encryptParams;
                } catch (Exception e) {
//                    log.error("下载zip时 - 参数加密异常: ", e);
                    return;
                }

                // 302重定向
                response.sendRedirect(redirectUrl + urlParams);

            } else if (request.getRequestURI().indexOf("downFile") > -1) {
                    // 文件下载重定向
                    // 前端路径写为 /api/v1/downFile
                    String[] downPath = request.getRequestURI().split("&");
                    if (downPath.length >= 2) {
                        response.sendRedirect(downPath[1]);
                    }
            } else {
                // 其他请求处理
                chain.doFilter(request, response);
            }

        } catch (Exception e) {
            log.error("error!", e);
        }
//        log.info("myFilter end");
//        log.info("myFilter end之后" + request.getRequestURI());
    }

    @Override
    public void destroy() {

    }
}

